package com.fushenlan.epidemicControl.sms;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 配置文件加解密工具类
 *
 * @author Administrator
 * @date 2022/4/23 0:51
 */
@Slf4j
@Data
@Component
public class EncryptUtil {

    private static final String ALGORITHM = "PBEWithMD5AndDES";

    @Value("${jasypt.encryptor.password}")
    private String PSWD;


    /**
     * 加密
     *
     * @param context 明文
     */
    public String encrypt(String context) {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        // 加密的算法，这个算法是默认的
        config.setAlgorithm(ALGORITHM);
        //加密的密钥
        config.setPassword(PSWD);
        standardPBEStringEncryptor.setConfig(config);
        String encryptedText = standardPBEStringEncryptor.encrypt(context);
        log.info("Encrypted text:{}", encryptedText);
        return encryptedText;
    }

    /**
     * 解密
     *
     * @param encryptedText 密文 ENC(eTKWjnYaNGsHJ6kI4RCDJ2QQuKAlbxQX)
     */
    public String decrypt(String encryptedText) {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        // 加密的算法，这个算法是默认的
        config.setAlgorithm(ALGORITHM);
        //加密的密钥
        config.setPassword(PSWD);
        standardPBEStringEncryptor.setConfig(config);
        //如果是ENC(开头，以)结尾，去掉ENC()
        if (encryptedText.startsWith("ENC(") && encryptedText.endsWith(")")) {
            encryptedText = encryptedText.substring(3, encryptedText.length() - 1);
        }
        String decryptedText = standardPBEStringEncryptor.decrypt(encryptedText);
        log.info("Decrypted text:{}", decryptedText);
        return decryptedText;
    }
}
